package com.hatkisoft.LockFunction.listener;

import net.rim.device.api.system.Application;
import net.rim.device.api.system.GlobalEventListener;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.accessibility.AccessibilityManager;

import com.hatkisoft.LockFunction.ui.MyLockScreen;

public class GlobalEventListenerOfLockApp implements GlobalEventListener{

	public static final long POP_SCREEN = 0xdfc2ec06e96abddbL;
	public static final long PUSH_SCREEN = 0x7e16e3ef0bfb9e89L;
	
	private static final int LOCKSCREEN_PUSH_DELAY = 200;
	
	private static MyLockScreen lockScreen = new MyLockScreen();
	private static Object lock = new Object();
	
	public GlobalEventListenerOfLockApp() {
		AccessibilityManager.setAccessibleEventListener(new LockScreenListener());
		Application.getApplication().addKeyListener(new GlobalKeyListenerOfLockApp());
	}
	
	public void eventOccurred(long guid, int data0, int data1, Object object0, Object object1) {
		if (guid == POP_SCREEN) {
			popScreen();
		} else if (guid == PUSH_SCREEN) {
			pushScreen();
		} 
	}
	
	private void popScreen(){
		if (lockScreen.isDisplayed() == false) 
			return;
		UiApplication.getUiApplication().popScreen(lockScreen);
	}
	
	private static synchronized void pushScreen() {
		new Thread() {
			public void run() {
				synchronized (lock) {
					try {
						
						if (lockScreen.isDisplayed()) 
							return;
						sleep(LOCKSCREEN_PUSH_DELAY);
						synchronized (UiApplication.getEventLock()) {
							UiApplication.getUiApplication().pushGlobalScreen(lockScreen, -99999, 0);
						}
						
					} catch (InterruptedException e) {
					}
				}
			};
		}.start();
	}
}
